<?php
/**
* alltosun.com 邮件、短信 派送 dispatch_helper.php
* ============================================================================
* 版权所有 (C) 2009-2012 北京互动阳光科技有限公司，并保留所有权利。
* 网站地址: http://www.alltosun.com
* ----------------------------------------------------------------------------
* 许可声明：这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
* ============================================================================
* $Author: 钱有明 (qianym@alltosun.com) $
* $Date: 2012-9-20 下午2:56:55 $
* $Id: dispatch_helper.php 28827 2014-02-22 08:10:48Z qianym $
*/

class dispatch_helper
{
    /**
     * 发信通知、邮件、短信
     * @param int $type 1:只发通知, 2:通知与邮件, 3:通知邮件与短信
     * @return boolean
     */
    public static function send($log_id = 0, $version_id = 0, $type = 2)
    {
        if (empty($log_id) && empty($version_id)) {
            return FALSE;
        }

        $intro_arr = array();
        $res_info  = array();
        if ($log_id) {
            $log_info = get_res_info('log', $log_id);
            if (empty($log_info)) {
                return FALSE;
            }

            $res_info = get_res_info($log_info['res_name'], $log_info['res_id']);
            if (empty($res_info)) {
                return FALSE;
            }

            $intro_arr = log_helper::generate_log_info($log_id);

            // 如果是知识
        } elseif ($version_id) {
            return dispatch_helper::send_by_knowledge_version($version_id, $type);
        }

        if (empty($res_info) || !isset($intro_arr['log_intro']) || empty($intro_arr['log_intro'])) {
            return FALSE;
        }

        $res_name = $log_info['res_name'];
        $real_res_info = $res_info;

        if ('comment' == $log_info['res_name']) {
            if (empty($res_info['res_name']) || empty($res_info['res_id'])) {
                return FALSE;
            }

            $real_res_info = get_res_info($res_info['res_name'], $res_info['res_id']);
            if (!$real_res_info) {
                return FALSE;
            }

            $res_name = $res_info['res_name'];
        }

        $app_id = app_helper::get_app_id($res_name);

        //$notice_content .= '：<a href="'.AnUrl($log_info['res_name'], $log_info['res_id']).'">'.display_title($log_info['res_name'], $log_info['res_id']).'</a>';
        // 如果是工作日志，取出所有日志发布者与他的部门leader
        if ($res_name == 'work') {
            $user_ids = follower_helper::get_follower_ids('work', $real_res_info['id']);
            array_push($user_ids, $real_res_info['user_id']);
            if (isset($real_res_info['assign_id']) && $real_res_info['assign_id']) {
                array_push($user_ids, $real_res_info['assign_id']);
            }
            $user_ids = array_unique($user_ids);

            // 如果是考勤，取出考勤发布者与所有人事
        } else if ($res_name == 'attendance') {
            $human_ids = role_helper::get_user_ids_by_type(12);
            array_push($human_ids, $real_res_info['user_id']);
            $user_ids = array_unique($human_ids);

            // 如果是文件，取出所有协作人
        } else if (in_array($res_name, array('file', 'dir'))) {
            $user_ids = follower_helper::get_follower_ids($res_name, $real_res_info['id']);

            // 任务
        } else if ($res_name == 'task') {
            $user_ids = follower_helper::get_follower_ids($res_name, $real_res_info['id']);
            array_unshift($user_ids, $real_res_info['assign_id']);
            array_unshift($user_ids, $real_res_info['user_id']);
            $user_ids = array_unique($user_ids);

            // 其它资源
        } else {
            $user_ids = follower_helper::get_follower_ids($res_name, $real_res_info['id']);
        }
        //an_dump($user_ids, $res_info, $real_res_info);
        //return ;
        //exit;
        //an_dump($intro_arr['detail_list']);
        $user_ids = array_unique($user_ids);
        foreach ($user_ids as $v) {
            if (empty($v)) {
                continue;
            }
            if ($v == $log_info['op_id']) {
                continue;
            }
            if (ONDEV) {
                $user_ids = array_diff($user_ids, array(1));
            }

            // 如果是协作某文件，只给新的协作人和文件的所有者发通知与邮件
            if ($log_info['real_res_name'] == 'follower') {
                if (empty($log_info['difference'])) {
                    return FALSE;
                }
                $difference = unserialize($log_info['difference']);
                if ($log_info['res_name'] == 'file') {
                    if ($difference['res'] == 'user_id' && $v != $difference['id'] && $real_res_info['user_id'] != $v) {
                        //if ($real_res_info['user_id'] != $v) {
                        continue;
                    }

                    // 如果任务新加一个关注，只给新加的这人，及任务发布人与外理人发消息
                } elseif ($log_info['res_name'] == 'task') {
                    if (isset($difference[0]) && count($difference) == 1 && $v != $difference[0] && $res_info['user_id'] != $v && $res_info['assign_id'] != $v) {
                        //if ($real_res_info['user_id'] != $v) {
                        continue;
                    }
                }
            }

            // 如果是工作日志的批阅，只通知给日志发布人
            if ($res_name == 'work' && $log_info['real_field'] == 'work_status') {
                if ($v != $real_res_info['user_id']) {
                    continue;
                }
            }

            $notice_arr = array(
                    'app_id'     => $app_id,
                    'to_user_id' => $v,
                    'content'    => user_helper::display_name($log_info['op_id']).$intro_arr['notification_intro']
            );

            // 发通知
            $id = _widget('notification')->create($notice_arr);

            if (array_key_exists($res_name.'_num', message_config::$message_type)) {
                message_helper::update_message_unread_num($v, $res_name.'_num', 'add', 1);
            }

            $user_info = user_helper::get_user_info($v);
            // 操作人
            $operator  = user_helper::display_name($log_info['op_id']);
            Response::assign('operator', $operator);

            // 发邮件 ---------------------------------------------------------------------------
            if ($type == 2 && isset($user_info['email']) && $user_info['email']) {
                // 任务的邮件
                if ($log_info['res_name'] == 'task') {
                    $task_info = $res_info;

                    if ($log_info['real_field'] == 'assign') {
                        $template_title = 'add';
                    } elseif ($log_info['real_field']) {
                        $template_title = $log_info['real_field'];
                    } else {
                        $template_title = $log_info['real_res_name'];
                    }
                    // 如果是伪删除任务，调用删除模板
                    if ($template_title == 'status' && $log_info['action'] == 'update') {
                        $template_title = 'delete';
                    }

                    // 评论列表
                    $comment_list = _widget('comment')->get_list(array('res_name'=>'task', 'res_id'=>$task_info['id']), 'ORDER BY `id` DESC ');

                    Response::assign('log_info', $log_info);
                    Response::assign('log_detail_info', isset($intro_arr['detail_list'])?$intro_arr['detail_list']:array());
                    Response::assign('task_info', $task_info);
                    Response::assign('comment_list', $comment_list);
                    Response::assign('follower_ids', $user_ids);

                    $follower_count = follower_helper::get_follower_count('task', $task_info['id']);
                    $follower_list = follower_helper::get_follower_ids('task', $task_info['id'], 1);
                    Response::assign('follower_count', $follower_count);
                    Response::assign('follower_list', $follower_list);

                    // 获取短信模版和邮件模版
                    $template_path = MODULE_PATH."/dispatch/template/";

                    $email_title = Response::fetch($template_path."email/task/task_title.html");
                    $email_content = Response::fetch($template_path."email/task/task_".$template_title."_content.html");
                    $email_content .= Response::fetch($template_path."email/task/task_summary.html");

                // 评论的通知
                } else if ($log_info['res_name'] == 'comment') {
                    $email_title = $real_res_info['title'];
                    if (empty($email_title) && isset($res_info) && $res_info && $res_info['res_name'] == 'work') {
                        $email_title = user_helper::display_name($real_res_info['user_id']).'的工作日志'.$real_res_info['work_time'];
                    }
                    if ($res_name == 'task' && $real_res_info['group_id']) {
                        $email_title = '['.display_title('group', $real_res_info['group_id']).']'.$email_title;
                    }

                    // 评论列表
                    $comment_list = _widget('comment')->get_list(array('res_name'=>$res_info['res_name'], 'res_id'=>$res_info['res_id']), 'ORDER BY `id` DESC ');

                    Response::assign('log_info', $log_info);
                    Response::assign('log_detail_info', isset($intro_arr['detail_list'])?$intro_arr['detail_list']:array());
                    Response::assign('res_name', $res_info['res_name']);
                    Response::assign('res_info', $res_info);
                    Response::assign('real_res_info', $real_res_info);
                    Response::assign('comment_list', $comment_list);
                    Response::assign('follower_ids', $user_ids);

                    if ($res_info['res_name'] == 'task') {
                        $follower_count = follower_helper::get_follower_count('task', $real_res_info['id']);
                        $follower_list = follower_helper::get_follower_ids('task', $real_res_info['id'], 1);
                        Response::assign('follower_count', $follower_count);
                        Response::assign('follower_list', $follower_list);
                    }

                    $template_path = MODULE_PATH."/dispatch/template/";

                    $email_content  = Response::fetch($template_path."email/comment/content.html");
                    $email_content .= Response::fetch($template_path."email/comment/summary.html");

                    // 其它资源的邮件
                } else {
                    $email_title = $res_info['title'];
                    if (empty($email_title) && isset($log_info) && $log_info && $log_info['res_name'] == 'work') {
                        $email_title = user_helper::display_name($real_res_info['user_id']).'的工作日志'.$res_info['work_time'];
                    }
                    $email_content = $intro_arr['mail_intro'];
                    if (isset($log_info) && $log_info) {
                        $email_content = user_helper::display_name($log_info['op_id']).$intro_arr['mail_intro'];
                    }

                    // 评论列表
                    $comment_list = _widget('comment')->get_list(array('res_name'=>$log_info['res_name'], 'res_id'=>$log_info['res_id']), 'ORDER BY `id` DESC ');

                    Response::assign('res_name', $log_info['res_name']);
                    Response::assign('real_res_info', $real_res_info);
                    Response::assign('comment_list', $comment_list);
                    Response::assign('follower_ids', $user_ids);

                    $template_path = MODULE_PATH."/dispatch/template/";

                    $email_content .= Response::fetch($template_path."email/comment/summary.html");
                }

                //dispatch_helper::send_email($user_info['email'], $email_title, $email_content);
                queue_helper::queue_add('email', array('to_user_id'=>$user_info['id'], 'email'=>$user_info['email'], 'title'=>$email_title, 'content'=>$email_content));
            }

            // 发短信
            if ($type == 3) {

            }
        }

        return TRUE;
    }

    public static function send_by_knowledge_version($version_id, $type = 2)
    {
        $version_info = get_res_info('knowledge_version', $version_id);
        if (!$version_info) {
            return FALSE;
        }
        $app_id = app_helper::get_app_id('knowledge');
        $user_ids = follower_helper::get_follower_ids('knowledge', $version_info['knowledge_id']);
        if (!$user_ids) {
            return FALSE;
        }

        $version_info['is_dispatch'] = 1;
        $intro_arr = knowledge_helper::show_version_info($version_info);

        foreach ($user_ids as $v) {
            if (empty($v)) {
                continue;
            }
            if ($v == $version_info['user_id']) {
                continue;
            }

            $notice_arr = array(
                    'app_id'     => $app_id,
                    'to_user_id' => $v,
                    'content'    => user_helper::display_name($version_info['user_id']).$intro_arr['notification_intro']
            );

            if ($v == 15) {
                //var_dump($user_ids, $intro_arr);
            }
            // 发通知
            $id = _widget('notification')->create($notice_arr);

            if (array_key_exists('knowledge_num', message_config::$message_type)) {
                message_helper::update_message_unread_num($v, 'knowledge_num', 'add', 1);
            }

            $user_info = user_helper::get_user_info($v);
            // 发邮件 ---------------------------------------------------------------------------
            if ($type == 2 && isset($user_info['email']) && $user_info['email']) {

                $email_title = $version_info['title'];
                $email_content = $intro_arr['mail_intro'];
                $email_content = user_helper::display_name($version_info['user_id']).$intro_arr['mail_intro'];

                //dispatch_helper::send_email($user_info['email'], $email_title, $email_content);
                queue_helper::queue_add('email', array('to_user_id'=>$user_info['id'], 'email'=>$user_info['email'], 'title'=>$email_title, 'content'=>$email_content));
            }

            // 发短信
            if ($type == 3) {

            }
        }
    }

    /**
     * 得到邮件（短信）标题与内容模板
     * @param string $template_title 模板标题
     * @param string $type email:邮件 sms:短信
     * @return string
     */
    public static function get_dispatch_template($template_title, $params, $type = 'email')
    {
        $template_title = AnFilter::filter_string($template_title);
        if (empty($template_title)) {
            return '';
        }
        if (!$params || !is_array($params)) {
            return '';
        }

        // 获取短信模版和邮件模版
        $template_path = MODULE_PATH."/dispatch/template/".$type.'/'.$template_title.'.html';
        if (!file_exists($template_path)) {
            return '';
        }

        foreach ($params as $k=>$v) {
            Response::assign($k, $v);
        }

        return Response::fetch($template_path);
    }

    /**
     * 发送邮件函数
     * @param string $email 邮箱地址
     * @param array $search 被替换的内容
     * @param array $replace 替换的内容
     */
    public static function send_email($email, $title = '', $content = '', $company_id = 0)
    {
        if (in_array($company_id, array(0, 1))) {
            $mail_list = dispatch_config::$send_mail_list;
            // 随机取一个邮箱
            $mail_key = array_rand($mail_list, 1);
            $mail_info = array();
            if ($mail_key && isset($mail_list[$mail_key])) {
                $mail_info = $mail_list[$mail_key];
            }
            if (!$mail_info || !isset($mail_info['mail'])) {
                $mail_info = $mail_list[0];
            }

            $mail_host = $mail_info['mail_host'];
            $send_mail = $mail_info['mail'];
            $pwd       = $mail_info['pwd'];
            $port      = isset($mail_info['port'])?$mail_info['port']:0;
        } else {
            $mail_host = 'smtp.gmail.com'; 
            $send_mail = 'ace@harkhark.com.au';
            $pwd       = '2Eaf@L96';
            $port      = 465;
        }

        //var_dump($mail_info);
        $content .= '<div style="display:none;">'.date('Y-m-d H:i:s').rand(1, 10).time().rand(1, 10).substr($send_mail, 0, 8).'</div>';

        // 实例化phpmailer
        $mail = new PHPMailer();
        // 设置发送邮件的协议：SMTP
        $mail->IsSMTP();
        // 发送邮件的服务器
        //$mail->Host = "smtp.exmail.qq.com";
        $mail->Host = $mail_host;
        //端口
        if ($port) {
            $mail->SMTPSecure = "ssl"; // Gmail的SMTP主机需要使用SSL连接
            $mail->Port = $port;
        }
        // 打开SMTP
        $mail->SMTPAuth = true;
        // SMTP账户
        $mail->Username = $send_mail;
        //是否使用HTML格式
        $mail->IsHTML(true);
        // SMTP密码
        $mail->Password = $pwd;
        $mail->From = $mail->Username;
        $mail->FromName = "ACE";
        $mail->AddAddress("$email", "");
        //设置字符集编码
        $mail->CharSet = "UTF-8";
        $mail->Subject = "=?UTF-8?B?".base64_encode($title)."?=";
        //邮件内容（可以是HTML邮件）
        $mail->Body = $content;
        if (!$mail->Send()) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 发送邮件函数
     * @param string $email 邮箱地址
     * @param array $search 被替换的内容
     * @param array $replace 替换的内容
     */
    public static function send_email_bak($email, $title = '', $content = '', $send_mail = '')
    {
        /*$headers = "Content-type:text/html; charset=utf-8"."\r\n";
         $headers .= "From: ".ADMIN_EMAIL;//ADMIN_EMAIL

        $title = "=?UTF-8?B?".base64_encode($title)."?=";
        mail($email, $title, $content, $headers);
        return;*/

        // 实例化phpmailer
        $mail = new PHPMailer();
        // 设置发送邮件的协议：SMTP
        $mail->IsSMTP();
        // 发送邮件的服务器
        //$mail->Host = "smtp.exmail.qq.com";
        $mail->Host = "smtp.163.com";
        // 打开SMTP
        $mail->SMTPAuth = true;
        // SMTP账户
        $mail->Username = "acewebsend@163.com";
        //是否使用HTML格式
        $mail->IsHTML(true);
        // SMTP密码
        $mail->Password = "alltosun";
        $mail->From = $mail->Username;
        $mail->FromName = "ACE";
        $mail->AddAddress("$email", "");
        //设置字符集编码
        $mail->CharSet = "UTF-8";
        $mail->Subject = "=?UTF-8?B?".base64_encode($title)."?=";
        //邮件内容（可以是HTML邮件）
        $mail->Body = $content;
        if (!$mail->Send()) {
            return false;
        } else {
            return true;
        }
    }
}
?>